package com.jumi.microservice.controller;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jm.member.common.api.volidator.Validator;
import com.jm.member.common.core.exception.BaseException;
import com.jm.member.common.core.utils.DelFlag;
import com.jm.member.common.core.utils.ServletUtils;
import com.jm.member.common.core.web.page.TableDataInfo;
import com.jumi.microservice.aspectj.AdminChangeUserLogAspect;
import com.jumi.microservice.common.base.dto.ResponseResult;
import com.jumi.microservice.datasource.annotation.AdminChangeUserLog;
import com.jumi.microservice.dto.reponse.JmUserReponse;
import com.jumi.microservice.dto.request.JmUserQueryRequest;
import com.jumi.microservice.dto.request.JmUserUpdateRequest;
import com.jumi.microservice.dto.request.UserFollowLogUpdateRequest;
import com.jumi.microservice.entity.JmAdminChangeUserLog;
import com.jumi.microservice.entity.JmUser;
import com.jumi.microservice.entity.JmUserLevelChangeLog;
import com.jumi.microservice.entity.JmUserTeam;
import com.jumi.microservice.enums.*;
import com.jumi.microservice.service.*;
import com.jumi.microservice.util.PasswordUtils;
import com.jumi.microservice.util.RegexUtils;
import com.jumi.microservice.util.WrapperUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 会员表 前端控制器
 * </p>
 *
 * @author 要挑客户管理团队
 * @since 2020-07-14
 */
@RestController
@RequestMapping("/jm-user")
@Transactional
@Api(value = "会员管理", tags = {"会员操作接口"})
public class JmUserController {

    @Autowired
    IJmUserService userService;

    @Autowired
    IJmAdminChangeUserLogService userLogService;

    @Autowired
    JmAdminUserFollowLogController followLogController;

    @PostMapping("/saveUser")
    @ApiOperation("添加会员")
    public ResponseResult saveUser(@Validated(Validator.SaveValidator.class) JmUserUpdateRequest request) throws BaseException {
        QueryWrapper qw = new QueryWrapper<>().eq("mobile", request.getMobile());
        int count = userService.count(qw);
        if (count > 0) {
            return ResponseResult.error("此用户已存在！");
        }
        String passwd = request.getPasswd();
        String paypwd = request.getPaypwd();
        passwd = StrUtil.isEmpty(passwd) ? "123456" : passwd;
        paypwd = StrUtil.isEmpty(paypwd) ? "123456" : paypwd;
        request.setPasswd(PasswordUtils.passwd(passwd));
        request.setPaypwd(PasswordUtils.passwd(paypwd));
        if (ObjectUtil.isEmpty(request.getAvatar()))
            request.setAvatar(
                    "http://img.jumituangou.com/clientUse/public/defaultimg.png"
            );
        JmUser jmUser = userService.packUser(request);
        userService.saveUser(jmUser);
        String upUserMobile = request.getUpUserMobile();
        if (StrUtil.isNotEmpty(upUserMobile)) {
            bindRelation(0, upUserMobile, jmUser.getId(), SourceType.后台绑定);
        }
        return ResponseResult.success();
    }

    @PostMapping("/updateUser")
    @ApiOperation("更新会员信息")
    public ResponseResult updateUser(@Validated(Validator.UpdateValidator.class) JmUserUpdateRequest request) throws BaseException {
        return userService.updateUser(request, null);
    }


    @PostMapping("/updateUserStatus")
    @ApiOperation(value = "更新会员状态")
    @AdminChangeUserLog("更新会员状态")
    public ResponseResult updateUserStatus(Integer uid,
                                           @ApiParam(value = "1=允许登录,2=允许购买,3=允许举报,4=允许授权", type = "Integer", required = true) @RequestParam Integer allowType) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("id", uid);
        wrapper.select("id", "allow_authorize", "allow_login", "allow_buy", "allow_report");
        JmUser byId = userService.getOne(wrapper);
        if (ObjectUtil.isNull(byId)) return ResponseResult.error("未查询到相关记录！");
        switch (allowType) {
            case 1:
                byId.setAllowLogin(byId.getAllowLogin().equals(CommonEnum.是) ? CommonEnum.否 : CommonEnum.是);
                break;
            case 2:
                byId.setAllowBuy(byId.getAllowBuy().equals(CommonEnum.是) ? CommonEnum.否 : CommonEnum.是);
                break;
            case 3:
                byId.setAllowReport(byId.getAllowReport().equals(CommonEnum.是) ? CommonEnum.否 : CommonEnum.是);
                break;
            case 4:
                byId.setAllowAuthorize(byId.getAllowAuthorize().equals(CommonEnum.是) ? CommonEnum.否 : CommonEnum.是);
                break;
        }
        byId.setUpdateTime(LocalDateTime.now());
        userService.updateById(byId);
        AdminChangeUserLogAspect.setBack("更新会员状态", uid);//添加用户更改日志
        return ResponseResult.success();
    }


    @PostMapping("/getUserDataInfo")
    @ApiOperation("查询会员分页")
    public TableDataInfo<JmUserReponse> getUserDataInfo(JmUserQueryRequest queryRequest,
                                                        Integer size, Integer current) {
        Page page = new Page(current, size);
        QueryWrapper wrapper = WrapperUtil.getWrapper(null, queryRequest);
        wrapper.orderByDesc("id");
        String userStatus = queryRequest.getUserStatus();
        if (StrUtil.isNotEmpty(userStatus)) {
            wrapper.eq(userStatus, CommonEnum.否);
        }
        page = userService.getPage(page, wrapper);
        return PageService.getDataTableInfo(page);
    }


    @PostMapping("/cancelUser")
    @ApiOperation("注销会员")
    public ResponseResult cancelUser(String ids, String cancelBackup) {
        Long adminId = ServletUtils.getLoginId();
        String adminName = ServletUtils.getLoginName();

        String[] split = ids.split(",");
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.in("id", split);
        List<JmUser> list = userService.list(wrapper);
        List<JmAdminChangeUserLog> logs = new ArrayList<>();

        if (list.size() == 0) return ResponseResult.error("未查询到相关记录！");

        list.stream().forEach(u -> {
            u.setUpdateTime(LocalDateTime.now());
            u.setStatus(Status.关闭);
            u.setAllowLogin(CommonEnum.否);
            u.setAllowAuthorize(CommonEnum.否);
            u.setAllowReport(CommonEnum.否);
            u.setAllowBuy(CommonEnum.否);
            //添加用户修改日志。
            LocalDateTime now = LocalDateTime.now();
            JmAdminChangeUserLog log = new JmAdminChangeUserLog(u.getId(), "注销账号", cancelBackup, adminId, now, now, DelFlag.normal, adminName);
            logs.add(log);
            //添加用户跟踪日志
            UserFollowLogUpdateRequest request = new UserFollowLogUpdateRequest();
            request.setUid(u.getId());
            request.setBackup(cancelBackup);
            request.setType("注销会员");
            followLogController.saveLog(request);
        });
        userLogService.saveBatch(logs);
        return ResponseResult.success(userService.updateBatchById(list));
    }


    @PostMapping("/bindRelation")
    @ApiOperation(value = "绑定上下级")
    public ResponseResult bindRelation(
            @ApiParam(value = "0=绑定上级,1=绑定下级", type = "Integer", example = "0") @RequestParam Integer type,
            String mobile, Integer uid, SourceType sourceType) {
        if (StrUtil.isEmpty(mobile))
            return ResponseResult.error("手机号不可为空！");
        if (!RegexUtils.isMobile(mobile))
            return ResponseResult.error("手机号格式错误!");
        JmUser user = userService.getById(uid);
        JmUser bindUser = userService.getUserByMobile(mobile);
        userService.checkBindUser(user, bindUser, type);
        //--执行绑定逻辑
        if (ObjectUtil.isNotNull(sourceType)) {
            if (type.equals(0)) {
                //user=本人
                //bindUser=上级
                return userService.bindUp(user, bindUser, sourceType);
            } else if (type.equals(1)) {
                return userService.bindDown(user, bindUser, sourceType);
            }
        }
        return ResponseResult.error("无此类型!");
    }


    @PostMapping("/getUserInfo")
    @ApiOperation("获取单个用户详细信息")
    @ApiImplicitParam(name = "uid",value = "查询的用户Id")
    public ResponseResult getUserInfoById(Integer uid) {
        JmUserUpdateRequest userInfoById = userService.getUserInfoById(uid);
        if (ObjectUtil.isNotNull(userInfoById)) {
            return ResponseResult.success(userInfoById);
        }
        return ResponseResult.error("未查询到相关记录!");
    }

    @GetMapping("/getUserInfoDetail")
    @ApiOperation("获取单个用户详细信息->客服调用")
    @ApiImplicitParam(name = "uid",value = "查询的用户Id")
    public ResponseResult getUserInfoDetail(Integer uid) {
        Page page = new Page(1, 1);

        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("status", 1);
        wrapper.eq("id", uid);
        page = userService.getPage(page, wrapper);
        List<JmUserReponse> list=page.getRecords();
        if(ObjectUtil.isNotEmpty(list))
            return ResponseResult.success(list.get(0));
        return ResponseResult.error("未查询到相关记录!");
    }

    @Autowired
    IJmUserTeamService teamService;

    @Autowired
    IJmUserLevelChangeLogService userLevelChangeLogService;

    @PostMapping("/changeUserLevel")
    @ApiOperation("更改用戶等级")
    @Transactional
    public ResponseResult changeUserLevel(Integer uid, Integer level, String cause) {
        JmUser byId = userService.checkUserExist(uid);
        Long adminId = ServletUtils.getLoginId();
        String adminName = ServletUtils.getLoginName();

        Level changeLevel = Level.getLevelByValue(level);
        Level originalLevel = byId.getLevel();
        if (!ObjectUtil.equal(changeLevel, originalLevel)) {
            GradeEnum gradeEnum = level < originalLevel.getValue() ? GradeEnum.降级 : GradeEnum.升级;

            //更新用户等级日志
            JmUserLevelChangeLog changeLog = new JmUserLevelChangeLog(uid, byId.getLevel(), changeLevel, byId.getInviterId(), gradeEnum, LevelChangeEnum.后台更改等级
                    , adminId, "后台修改用户等级", adminId, adminName, DelFlag.normal, LocalDateTime.now(), LocalDateTime.now());

            byId.setUpdateTime(LocalDateTime.now());
            byId.setLevel(changeLevel);
            // 12-03 根据产品需求  因要求后台修改等级不会因用户产生售后而降级,故同时提升原始等级 originlevel
            byId.setOriginLevel(changeLevel);
            //获取用户的team信息
            List<JmUserTeam> list = teamService.getMySupers(uid);
            for (JmUserTeam team : list) {
                team.setAdminId(adminId);
                team.setAdminName(adminName);
                team.setLevel(changeLevel);
            }
            if (list.size() > 0) {
                teamService.updateBatchById(list);
            }
            userService.updateById(byId);
            //添加用户跟踪日志
            UserFollowLogUpdateRequest request = new UserFollowLogUpdateRequest();
            request.setUid(uid);
            request.setBackup(cause);
            request.setType("更改等级");
            followLogController.saveLog(request);
            userLevelChangeLogService.save(changeLog);
            return ResponseResult.success();
        }

        return ResponseResult.error("未查询到相关记录!");
    }


    @PostMapping("/unWechatBind")
    @ApiOperation("解绑微信")
    public ResponseResult unWechatBind(String uid) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.in("id", uid.split(","));
        List<JmUser> list = userService.list(wrapper);
        List<JmAdminChangeUserLog> logs = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(list)) {
            list.stream().forEach(u -> {
                u.setWeixinUnionid("");
                u.setWxOpenid("");
                u.setWechatNum("");
                u.setUpdateTime(LocalDateTime.now());
                //添加用户修改日志。
                LocalDateTime now = LocalDateTime.now();
                JmAdminChangeUserLog log = new JmAdminChangeUserLog(u.getId(), "解绑微信", "解绑微信", ServletUtils.getLoginId(), now, now, DelFlag.normal, ServletUtils.getLoginName());
                logs.add(log);
            });
            userService.updateBatchById(list);
            userLogService.saveBatch(logs);
            return ResponseResult.success();
        }
        return ResponseResult.error("未查询到相关数据!");
    }
}
